package com.cheyunkeji.er.activity.evaluate;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.adapter.MyBaseAdapter;
import com.cheyunkeji.er.adapter.citymodel.CarBrandSortAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.evaluate.CarInfo;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.model.CarBrandModel;
import com.cheyunkeji.er.utils.CarBrandPinyinComparator;
import com.cheyunkeji.er.utils.PinyinComparator;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.cheyunkeji.er.view.cityview.SideBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;

public class SelectCarInfoActivity extends BaseActivity
    implements AdapterView.OnItemClickListener, SideBar.OnTouchingLetterChangedListener {

  private static final int PARAMS_LEVEL_CAR_BRAND = 1;
  private static final int PARAMS_LEVEL_CAR_SERIES = 2;
  private static final int PARAMS_LEVEL_CAR_MODEL = 3;
  private static final String TAG = SelectCarInfoActivity.class.getSimpleName();

  @BindView(R.id.v_topbar)
  TopBar vTopbar;

  @BindView(R.id.lv_content)
  ListView lvContent;

  @BindView(R.id.activity_select_car_info)
  LinearLayout activitySelectCarInfo;

  @BindView(R.id.ll_car_model_tip)
  LinearLayout ll_car_model_tip;
  @BindView(R.id.tv_car_model_vv)
  TextView tv_car_model_vv;

  @BindView(R.id.sidebar)
  SideBar sideBar;

  private List<CarInfo.CarBrand> brandListData;
  private CarBrandSortAdapter adapter;
  private ArrayList<CarBrandModel> modelList;
  private ArrayList<CarInfo.CarSeries> seriesList;
  private CarSeriesListAdapter carSeriesAdapter;

  private int selectLevel;
  private ArrayList<CarInfo.CarModel> carModelList;
  private CarModelListAdapter carModelAdapter;
  private String model_mark;

  @Override
  protected void init() {
    setContentView(R.layout.er_activity_select_car_info);
    ButterKnife.bind(this);
  }

  @Override
  protected void initView() {
    selectLevel = getIntent().getIntExtra(Constants.CAR_BRAND_LEVEL_BRAND, PARAMS_LEVEL_CAR_BRAND);
    if(getIntent().hasExtra("Mark")){
      model_mark = getIntent().getStringExtra("Mark");
    }
    if (selectLevel == PARAMS_LEVEL_CAR_BRAND) {
      vTopbar.setTitle("选择车辆品牌");
      loadCarBrandList();
    } else if (selectLevel == PARAMS_LEVEL_CAR_SERIES) {
      vTopbar.setTitle("选择车系");
      if (!TextUtils.isEmpty(getIntent().getStringExtra("pid")))
        loadCarSeriesList(getIntent().getStringExtra("pid"));
    } else if (selectLevel == PARAMS_LEVEL_CAR_MODEL) {
      vTopbar.setTitle("选择车型");
      if (!TextUtils.isEmpty(getIntent().getStringExtra("pid")))
        loadCarModelList(getIntent().getStringExtra("pid"));
    }
    if (!TextUtils.isEmpty(model_mark)){
      ll_car_model_tip.setVisibility(View.VISIBLE);
      tv_car_model_vv.setText(model_mark);
    }

  }

  private void loadCarModelList(String pid) {
    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("level", String.valueOf(PARAMS_LEVEL_CAR_MODEL));
    params.put("pid", pid);

    ApiClient.postForm(
        HttpConstants.GET_CAR_BRAND_LIST,
        params,
        new RespCallback<List<CarInfo.CarModel>>() {
          @Override
          protected void onRequestFailed(String msg) {
            SToast.show(msg);
          }

          @Override
          protected void onSuccess(List<CarInfo.CarModel> data) {

            showCarModelList(data);
          }

          @Override
          public void onBefore(Request request, int id) {
            showDialog();
          }

          @Override
          public void onAfter(int id) {
            dismissDialog();
          }
        });
  }

  private void showCarModelList(List<CarInfo.CarModel> data) {
    if (null == data) return;
    carModelList = (ArrayList<CarInfo.CarModel>) data;
    carModelAdapter = new CarModelListAdapter(carModelList, this);
    lvContent.setAdapter(carModelAdapter);
    lvContent.setOnItemClickListener(this);
  }

  private void loadCarSeriesList(String pid) {
    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("level", String.valueOf(PARAMS_LEVEL_CAR_SERIES));
    params.put("pid", pid);

    ApiClient.postForm(
        HttpConstants.GET_CAR_BRAND_LIST,
        params,
        new RespCallback<List<CarInfo.CarSeries>>() {

          @Override
          protected void onRequestFailed(String msg) {

            SToast.show(msg);
          }

          @Override
          protected void onSuccess(List<CarInfo.CarSeries> data) {

            showCarSeriesList(data);
          }

          @Override
          public void onBefore(Request request, int id) {
            showDialog();
          }

          @Override
          public void onAfter(int id) {
            dismissDialog();
          }
        });
  }

  private void showCarSeriesList(List<CarInfo.CarSeries> data) {

    if (data == null) {
      return;
    }

    seriesList = (ArrayList<CarInfo.CarSeries>) data;
    carSeriesAdapter = new CarSeriesListAdapter(seriesList, this);
    lvContent.setAdapter(carSeriesAdapter);
    lvContent.setOnItemClickListener(this);
  }

  private void loadCarBrandList() {

    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("level", String.valueOf(PARAMS_LEVEL_CAR_BRAND));

    ApiClient.postForm(
        HttpConstants.GET_CAR_BRAND_LIST,
        params,
        new RespCallback<List<CarInfo.CarBrand>>() {

          @Override
          protected void onRequestFailed(String msg) {

            SToast.show(msg);
          }

          @Override
          protected void onSuccess(List<CarInfo.CarBrand> data) {

            setBrandListData(data);
          }

          @Override
          public void onBefore(Request request, int id) {
            showDialog();
          }

          @Override
          public void onAfter(int id) {
            dismissDialog();
          }
        });
  }

  private void setBrandListData(List<CarInfo.CarBrand> data) {

    if (null == data) return;

    brandListData = data;
    modelList = new ArrayList<>();

    ArrayList<String> letterList = new ArrayList<>();

    for (int i = 0; i < brandListData.size(); i++) {

      if (brandListData.get(i).getFletter().matches("[A-Z]")
          && !letterList.contains(brandListData.get(i).getFletter())) {
        letterList.add(brandListData.get(i).getFletter());
      }

      CarBrandModel model = new CarBrandModel();
      model.setName(brandListData.get(i).getTitle());
      model.setInitial(brandListData.get(i).getFletter());
      model.setId(brandListData.get(i).getId());
      modelList.add(model);
    }

    Collections.sort(letterList);
    sideBar.setIndexText(letterList);
    sideBar.setTextColor(Color.parseColor("#35404d"));
    sideBar.setVisibility(View.VISIBLE);

    Collections.sort(brandListData, new CarBrandPinyinComparator());

    Collections.sort(modelList, new PinyinComparator());

    adapter = new CarBrandSortAdapter(this, modelList);
    lvContent.setAdapter(adapter);

    sideBar.setOnTouchingLetterChangedListener(this);
    lvContent.setOnItemClickListener(this);
  }

  @Override
  protected void initData() {}

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    Intent intent = new Intent();

    switch (selectLevel) {
      case PARAMS_LEVEL_CAR_BRAND:
        CarBrandModel model = modelList.get(position);

        intent.putExtra(
            "CAR_BRAND", new CarInfo.CarBrand(model.getId(), model.getName(), model.getInitial()));
        setResult(RESULT_OK, intent);
        MyApplication.getInstance().removeActivity(this.getClass());
        finish();
        break;

      case PARAMS_LEVEL_CAR_SERIES:
        intent.putExtra("CAR_SERIES", seriesList.get(position));
        setResult(RESULT_OK, intent);
        MyApplication.getInstance().removeActivity(this.getClass());
        finish();
        break;

      case PARAMS_LEVEL_CAR_MODEL:
        intent.putExtra("CAR_MODEL", carModelList.get(position));
        setResult(RESULT_OK, intent);
        MyApplication.getInstance().removeActivity(this.getClass());
        finish();
        break;

      default:
        break;
    }
  }

  @Override
  public void onTouchingLetterChanged(String s) {

    // 该字母首次出现的位置
    int position = adapter.getPositionForSection(s.charAt(0));
    if (position != -1) {
      lvContent.setSelection(position);
    }
  }

  class CarSeriesListAdapter extends MyBaseAdapter {

    public CarSeriesListAdapter(ArrayList<CarInfo.CarSeries> dataList, Context context) {
      super(dataList, context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

      final ViewHolder holder;
      if (convertView == null) {
        convertView =
            LayoutInflater.from(context)
                .inflate(R.layout.er_car_source_city_selector_lv_item, null);
        holder = new ViewHolder(convertView);
        convertView.setTag(holder);
      } else {
        holder = (ViewHolder) convertView.getTag();
      }

      if (position % 2 != 0) convertView.setBackgroundColor(Color.parseColor("#fbfbfb"));
      else convertView.setBackgroundColor(Color.parseColor("#ffffff"));

      CarInfo.CarSeries itemBean = (CarInfo.CarSeries) dataList.get(position);
      holder.tvCityName.setText(itemBean.getTitle());

      return convertView;
    }

    class ViewHolder {
      @BindView(R.id.tv_city_name)
      TextView tvCityName;

      ViewHolder(View view) {
        ButterKnife.bind(this, view);
      }
    }
  }

  class CarModelListAdapter extends MyBaseAdapter {

    public CarModelListAdapter(ArrayList<CarInfo.CarModel> dataList, Context context) {
      super(dataList, context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

      final ViewHolder holder;
      if (convertView == null) {
        convertView =
            LayoutInflater.from(context)
                .inflate(R.layout.er_car_source_city_selector_lv_item, null);
        holder = new ViewHolder(convertView);
        convertView.setTag(holder);
      } else {
        holder = (ViewHolder) convertView.getTag();
      }

      if (position % 2 != 0) convertView.setBackgroundColor(Color.parseColor("#fbfbfb"));
      else convertView.setBackgroundColor(Color.parseColor("#ffffff"));

      CarInfo.CarModel itemBean = (CarInfo.CarModel) dataList.get(position);
      holder.tvCityName.setText(itemBean.getTitle());

      return convertView;
    }

    class ViewHolder {
      @BindView(R.id.tv_city_name)
      TextView tvCityName;

      ViewHolder(View view) {
        ButterKnife.bind(this, view);
      }
    }
  }
}
